package com.elinkway.infinitemovies.utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;

import com.elinkway.infinitemovies.application.MoviesApplication;
import com.elinkway.infinitemovies.async.MoviesHttpAsyncTask;
import com.elinkway.infinitemovies.bean.CloudLiteBean;
import com.elinkway.infinitemovies.bean.CloudLiteEpiBean;
import com.elinkway.infinitemovies.bean.Episode;
import com.elinkway.infinitemovies.bean.LiteAppLinkUrlInfo;
import com.elinkway.infinitemovies.bean.PlayData;
import com.elinkway.infinitemovies.bean.PlayRecord;
import com.elinkway.infinitemovies.bean.VideoDataBean;
import com.elinkway.infinitemovies.bigdata.BigDataApi;
import com.elinkway.infinitemovies.bigdata.BigDataConstants;
import com.elinkway.infinitemovies.dao.PlayRecordDao;
import com.elinkway.infinitemovies.http.api.MoviesHttpApi;
import com.elinkway.infinitemovies.http.parser.LiteAppLinkUrlParser;
import com.elinkway.infinitemovies.service.UpdateService;
import com.elinkway.infinitemovies.ui.activity.play.PlayerUtils;
import com.elinkway.infinitemovies.view.LiteProgressDialog;
import com.google.gson.Gson;
import com.le123.ysdq.BuildConfig;
import com.le123.ysdq.R;
import com.lvideo.http.bean.LVideoDataHull;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by 吴新荣 on 2015/12/21.
 * 影视大全中Lite App逻辑管理类
 */
public class LiteAppManager {

    private static final String LITE_APP_PACKAGE_NAME = "com.letv.android.client";
    private static final String LITE_APP_ACTIVITY_PLAY = "com.letv.android.client.activity.AlbumPlayActivity";
    public static final String LITE_APP_FILE_NAME = "liteletv01001am.apk";

    public static final String INFINITE_MOVIES = "infinitemovies";

    private static final String MANUFACTURER_LETV = "Letv";
    private static final String MANUFACTURER_LEMOBILE = "LeMobile";
    public static final String PCODE = "010111305";
    // 代理服务器对版本号的的要求是只需要一个正式版本的版本号，影视大全的版本号与基线版本不同，因此用6.3
    public static final String VERSION = "6.3";

//    private static final String LITE_APP_INSTALL_TIP = "因版权问题，需要安装影视大全高速播放器。";
    private static final String LITE_APP_INSTALL_TIP = "安装插件，观看视频将更流畅清晰、更省流量。";

    private static final String LITE_APP_INSTALL_PROGRESS_TIP = "组件正在加载，请稍后。。。";

    public boolean mLiteAppFuncSwitch = false;

    LiteAppLinkUrlReqTask mDownloadLiteAppTask;

    public static LiteProgressDialog progressDialog;

    public static final int DOWNLOAD_STATE_NONE = 0;    // 初始状态
    public static final int DOWNLOAD_STATE_DOWNLOADING = 1;    // 下载中
    public static final int DOWNLOAD_STATE_COMPLETE = 2;    // 下载完成
    public static final int DOWNLOAD_STATE_FAILED = 3;    // 下载失败
    private int mDownloadState = DOWNLOAD_STATE_NONE;  // 初始状态

    /**
     * 启动方式
     */
    public static final int LAUNCH_MODE_URI = 1;
    public static final int LAUNCH_MODE_ALBUM = 2;
    public static final int LAUNCH_MODE_VIDEO = 3;
    public static final int LAUNCH_MODE_DOWNLOAD = 4;
    public static final int LAUNCH_MODE_YUNPAN = 30;

    public static final String MLITESCHEME = "liteclient://mliteAction?";

    /**
     * 启动来源
     */
    private static final int LAUNCH_FROM_MSITE = 20;    // 该值和基线版本保持一致

    private static LiteAppManager mInstance;

    public static LiteAppManager getInstance() {
        if (null == mInstance) {
            mInstance = new LiteAppManager();
        }
        return mInstance;
    }

    /**
     * 启动LiteApp播放器，若不满足启动条件，则返回启动默认播放器标识
     *
     * @param context
     * @param video
     * @param position           剧集索引位置
     * @param shouldBackToCaller 离开播放页时是否返回到调用方的应用
     * @return liteAppLaunched
     */
    public boolean launchPlayer(Activity context, VideoDataBean video, int position, boolean shouldBackToCaller, boolean couldPlay) {
        boolean liteAppLaunched = false;
        if (getLiteAppFuncSwitch()) {
            if(video.getPlaySrcBean() != null && "1".equals(video.getPlaySrcBean().getPlayer())){
                if (isLVideoSiteVideo(video, position)) {
                    if (!isLVideoPhone()) {
                        /*
                         * 乐视手机预置了乐视视频领先版
                         * 领先版没有AlbumPlayActivity，
                         * 因此如果是乐视手机，则还是走影视大全原来的播放流程
                         * 只需让liteAppLaunched返回false
                         */
                        liteAppLaunched = true;
                        if (!couldPlay) {
                            return true;
                        }
                        if (!isLiteAppInstalled(context)) {
                            showConfirmDialog(context, video);
                        } else {
                            // 影视大全的aid带有站内前缀"1_"，使用时需要预先去除
                            long aid = Long.valueOf(video.getAid().substring(2));
                            long vid = parseVid(video, position);
                            if(isHasVersionLite(context)){
                                try {
                                    launchNewLite(context, aid, vid, LAUNCH_MODE_ALBUM, shouldBackToCaller);
                                }catch (Exception e){
                                    return false;
                                }
                            }else{
                                launch(context, aid, vid, LAUNCH_MODE_ALBUM, shouldBackToCaller);
                            }
                            // 播放上报统计
                            String reportKey = "name=play";
                            BigDataApi.bigDataAdReport(BigDataConstants.ACODE_CLICK, reportKey, context);
                            // Umeng统计 调起乐视视频（包括liteApp）
                            HashMap map = new HashMap();
                            map.put("source", video.getSubsrc());
                            map.put("premiere", SharePreferenceManager.getVaule(context, SharePreferenceManager.IS_FIRST_INVOKE_LITE, "1"));
                            UmengEventPoster.doPost(UmengEventPoster.LITEAPP_INVOKE, map);
                            SharePreferenceManager.saveVaule(context, SharePreferenceManager.IS_FIRST_INVOKE_LITE, "0");
//                            UmengEventPoster.doEventPost(UmengPostConstant.Play_LVideoApp);
                        }
                    }
                }else if(PlayerUtils.SITE_CLOUDDISK.equals(video.getSubsrc())){
                    if (!isLVideoPhone()) {
                        /*
                         * 乐视手机预置了乐视视频领先版
                         * 领先版没有AlbumPlayActivity，
                         * 因此如果是乐视手机，则还是走影视大全原来的播放流程
                         * 只需让liteAppLaunched返回false
                         */
                        if (!isLiteAppInstalled(context)) {
                            //如果云盘源吊起liteapp时还没有安装，直接走自己的播放器
//                            liteAppLaunched = true;
//                            showConfirmDialog(context, video);
                        } else {
                            if(isHasVersionLite(context)){
                                if (!couldPlay) {
                                    return true;
                                }
                                liteAppLaunched = true;
                                yunpanLaunch(context, video, position, LAUNCH_MODE_YUNPAN, shouldBackToCaller);
                                // 播放上报统计
                                String reportKey = "name=play";
                                BigDataApi.bigDataAdReport(BigDataConstants.ACODE_CLICK, reportKey, context);
                                // Umeng统计 调起乐视视频（包括liteApp）
                                HashMap map = new HashMap();
                                map.put("source", video.getSubsrc());
                                map.put("premiere", SharePreferenceManager.getVaule(context, SharePreferenceManager.IS_FIRST_INVOKE_LITE, "1"));
                                UmengEventPoster.doPost(UmengEventPoster.LITEAPP_INVOKE, map);
                                SharePreferenceManager.saveVaule(context, SharePreferenceManager.IS_FIRST_INVOKE_LITE, "0");
//                                UmengEventPoster.doEventPost(UmengPostConstant.Play_LVideoApp);
                            } else {

                            }
                        }
                    }
                } else {

                }
            }

        } else
            LogUtils.e(UpdateService.TAG, "detail liteApp switch is false");
        return liteAppLaunched;
    }

    private boolean isLVideoPhone() {
        boolean result = false;
        String manufacturer = android.os.Build.MANUFACTURER;
        if (!TextUtils.isEmpty(manufacturer)&& (manufacturer.equalsIgnoreCase(MANUFACTURER_LEMOBILE) ||
                manufacturer.equalsIgnoreCase(MANUFACTURER_LETV))) {
            result = true;
        }
        return result;
    }

    /**
     * 检测LiteApp安装状态
     *
     * @param context
     */
    public void checkInstallState(final Context context) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (getLiteAppFuncSwitch()) {
                    LogUtils.e(UpdateService.TAG, "LiteApp功能开关状态: 开启");
                    if (!isLiteAppInstalled(context)) {
                        LogUtils.e(UpdateService.TAG, "未安装Lite App");
                        if(NetWorkTypeUtils.getNetType() == NetWorkTypeUtils.NETTYPE_WIFI) {
                            // 未安装Lite App，且目录中无LiteApp包，则静默下载
                            if (isApkFileExist(context)) {
                                String filePath = getStoragePath(context) + "/" + LITE_APP_FILE_NAME;
                                LogUtils.e(UpdateService.TAG, "local exist apk and need delete");
                                String md5 = SharePreferenceManager.getVaule(context, SharePreferenceManager.LITE_APP_MD5, "");
                                if (TextUtils.isEmpty(md5)? true : md5.equals(MD5Utils.md5File(filePath))) {
                                    //已下载
                                } else {
                                    deleteApkFile(context);
                                    downloadSilent(context, false);
                                }
                            } else {
                                downloadSilent(context, false);
                            }
                        }
                    } else
                        LogUtils.e(UpdateService.TAG, "has install lvideo client");
                } else
                    LogUtils.e(UpdateService.TAG, "splash liteApp switch is false");
            }
        }).start();
    }

    private void deleteApkFile(Context context) {
        try {
            LogUtils.e(UpdateService.TAG, "deleteApkFile called");
            File file = new File(Environment.getExternalStorageDirectory(), LITE_APP_FILE_NAME);
//            String path = getStoragePath(context);
//            File file = new File(path + "/" + LITE_APP_FILE_NAME);
            if (file.exists()) {
                boolean isDelete = file.delete();
                LogUtils.e(UpdateService.TAG, "deleteApkFile delete status is " + isDelete);
            }
        } catch (Exception e) {
            LogUtils.e(UpdateService.TAG, "delete file catch exception and msg is " + e.getMessage());
        }
    }

    /**
     * 判断应用是否已安装
     *
     * @param context 场景上下文
     * @return
     */
    private static boolean isLiteAppInstalled(Context context) {
        boolean isInstalled = false;
        PackageInfo pi;
        try {
            pi = context.getPackageManager().getPackageInfo(LITE_APP_PACKAGE_NAME, 0);
        } catch (PackageManager.NameNotFoundException e) {
            pi = null;
            e.printStackTrace();
        }
        if (null != pi) {
            isInstalled = true;
        }
        return isInstalled;
    }

    /**
     * 判断是否安装对应版本的应用（支持云盘调liteapp）
     *
     * @param context 场景上下文
     * @return
     */
    private static boolean isHasVersionLite(Context context) {
        boolean isHasVersion = false;
        PackageInfo pi;
        try {
            pi = context.getPackageManager().getPackageInfo(LITE_APP_PACKAGE_NAME, 0);
        } catch (PackageManager.NameNotFoundException e) {
            pi = null;
            e.printStackTrace();
        }
        if (null != pi) {
            if(pi.versionName.startsWith("1.")){
                if(pi.versionCode >= 3){
                    isHasVersion = true;
                }
            }else if(pi.versionName.startsWith("6.")){
                if(pi.versionCode >= 111){
                    isHasVersion = true;
                }
            }else{
                isHasVersion = true;
            }
//            isHasVersion = true;
        }
        return isHasVersion;
    }

    /**
     * 获取apk文件存储路径，需要考虑插有SD卡的情形
     *
     * @param context
     * @return
     */
    private static String getStoragePath(Context context) {
        String path = "";
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            path = context.getDir("updata", Context.MODE_WORLD_WRITEABLE | Context.MODE_WORLD_READABLE | Context.MODE_PRIVATE)
                    .getPath();
        } else {
            path = Environment.getExternalStorageDirectory().getPath();
        }
        return path;
    }

    /**
     * 获取Lite App文件所在路径
     */
    private static String getFilePath(Context context) {
        return getStoragePath(context) + "/" + LITE_APP_FILE_NAME;
    }

    /**
     * 判断指定的apk是否已存储在特定的目录
     *
     * @return 存在返回true，否则返回false
     */
    private static boolean isApkFileExist(Context context) {
        try {
            String path = getStoragePath(context);
//            LogUtils.e(UpdateService.TAG, "存储路径 = " + path);
            File file = new File(path + "/" + LITE_APP_FILE_NAME);
            if (!file.exists()) {
                return false;
            }
        } catch (Exception e) {
            LogUtils.e(UpdateService.TAG, "read file error");
            return false;
        }
        return true;
    }

    private static String requestDownloadUrl() {

        return "";
    }

    /**
     * 静默下载lite app
     *
     * @param context
     */
    private void downloadSilent(Context context, boolean isToInstall) {
        if (mDownloadLiteAppTask != null) {
            mDownloadLiteAppTask.cancel();
        }
        mDownloadLiteAppTask = new LiteAppLinkUrlReqTask(context, isToInstall);
        mDownloadLiteAppTask.start();
        // 下载上报统计
        String reportKey = "name=download";
        BigDataApi.bigDataAdReport(BigDataConstants.ACODE_CLICK, reportKey, context);
    }

    /**
     * 显示安装确认对话框
     *
     * @param context
     */
    private void showConfirmDialog(final Activity context, final VideoDataBean video) {
        ((Activity) context).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                new AlertDialog.Builder(context)
                        .setMessage(LITE_APP_INSTALL_TIP)
                        .setTitle("提示")
                        .setCancelable(true)
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                dialogInterface.dismiss();
                                HashMap map = new HashMap();
                                if (video != null) {
                                    map.put("source", video.getSubsrc());
                                    map.put("action", "NO");
                                }
                                UmengEventPoster.doPost(UmengEventPoster.LITEAPP_INSTALL_PROMOTE, map);
                            }
                        })
                        .setPositiveButton("立即破解", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                HashMap map = new HashMap();
                                if (video != null) {
                                    map.put("source", video.getSubsrc());
                                    map.put("action", "YES");
                                }
                                UmengEventPoster.doPost(UmengEventPoster.LITEAPP_INSTALL_PROMOTE, map);
                                showNetDialog(context);
                            }
                        })
                        .create()
                        .show();
            }
        });
    }

    /**
     * 判断视频是否是乐视网站的视频
     *
     * @param video 视频对象
     * @return
     */
    private static boolean isLVideoSiteVideo(VideoDataBean video, final int position) {
        ArrayList<Episode> list = video.getEpisodeList();
        if (list.size() == 0) {
            return false;
        }
        Episode episode = video.getEpisodeList().get(position);
        // 有mid则表示是乐视源视频，否则为非乐视源视频
        return TextUtils.isEmpty(episode.getMid()) ? false : true;
    }

    private static PlayData genPlayData(VideoDataBean video, PlayRecord record) {
        Episode episode = video.getEpisodeList().get(0);
        PlayData playData = new PlayData(video, episode.getPorder(),
                record, UmengEventPoster.PLAYER_FROM_DETAIL);
        playData.setmPorderLists(video.getmPorderLists());

        return playData;
    }

    /**
     * 根据当前剧集在剧集列表中的位置，解析出vid
     *
     * @param video    剧集数据信息
     * @param position 剧集索引位置
     * @return 剧集vid
     */
    private static int parseVid(VideoDataBean video, final int position) {
        Episode ep = video.getEpisodeList().get(position);
        String playUrl = ep.getPlay_url();
        int begin = playUrl.lastIndexOf("/");
        String target = playUrl.substring(begin + 1);
        int end = target.lastIndexOf(".");
        int vid = Integer.valueOf(target.substring(0, end));
        return vid;
    }

    /**
     * 调起Lite App播放
     *
     * @param context
     * @param aid                剧集id
     * @param vid                视频id
     * @param launchMode         启动模式
     * @param shouldBackToCaller 离开播放页时是否返回到调用方的应用
     */
    private static void launch(Context context, long aid, long vid, int launchMode, boolean shouldBackToCaller) {
        Intent intent = new Intent();
        intent.setClassName(LITE_APP_PACKAGE_NAME, LITE_APP_ACTIVITY_PLAY);
        intent.putExtra("launchMode", launchMode);
        intent.putExtra("aid", (int) aid);
        intent.putExtra("vid", (int) vid);
        intent.putExtra("packageName", BuildConfig.APPLICATION_ID);
        intent.putExtra("from", LAUNCH_FROM_MSITE);
        intent.putExtra("ref", INFINITE_MOVIES);
        intent.putExtra("back", shouldBackToCaller);
        intent.putExtra("pcode", MoviesApplication.PLAYER_PCODE);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(intent);
    }
    /**
     * 调起Lite App播放
     *
     * @param context
     * @param aid                剧集id
     * @param vid                视频id
     * @param launchMode         启动模式
     * @param shouldBackToCaller 离开播放页时是否返回到调用方的应用
     */
    private static void launchNewLite(Context context, long aid, long vid, int launchMode, boolean shouldBackToCaller) throws Exception{
        String parmsString = "aid=" + aid + "&vid=" + vid + "&launchMode="+launchMode + "&packageName=" + BuildConfig.APPLICATION_ID +
                "&form="+ LAUNCH_FROM_MSITE + "&ref="+ INFINITE_MOVIES +"&back="+shouldBackToCaller+"&pcode="+MoviesApplication.PLAYER_PCODE;
        Uri uri = Uri.parse(MLITESCHEME + parmsString);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
//        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        try {
            context.startActivity(intent);
        }catch(Exception e){
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 调起Lite App播放
     *
     */
    private static void yunpanLaunch(Context context, VideoDataBean video, int position, int launchMode, boolean shouldBackToCaller) {
        PlayRecord playRecord = new PlayRecordDao(context).getByAid(video.getAid());

//        Intent intent = new Intent();
        String parmsString = "launchMode="+launchMode + "&packageName=" + BuildConfig.APPLICATION_ID +"&back="+shouldBackToCaller+"&pcode="+MoviesApplication.PLAYER_PCODE;
        Uri uri = Uri.parse(MLITESCHEME + parmsString);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
//        intent.setClassName(LITE_APP_PACKAGE_NAME, LITE_APP_ACTIVITY_PLAY);
//        intent.putExtra("launchMode", launchMode);
//        intent.putExtra("packageName", "com.le123.ysdq");
//        intent.putExtra("back", shouldBackToCaller);
        //TODO
        CloudLiteBean cloudLiteBean = new CloudLiteBean();
        cloudLiteBean.setYsdq_aid(video.getAid());
        cloudLiteBean.setName(video.getName());
        cloudLiteBean.setPlay_num(position);
        cloudLiteBean.setSubsrc(video.getSubsrc());
        cloudLiteBean.setPorder_list(video.getmPorderLists());
        cloudLiteBean.setCategory(video.getCategory());
        cloudLiteBean.setVt(video.getVt());
        cloudLiteBean.setPlay_quality("0");

        ArrayList<Episode> list = video.getEpisodeList();
        if (list != null && list.size() > 0) {
            Episode ep = list.get(position);
            if (null != playRecord) {
                if ((ep.getPorder().equals(playRecord.getPorder()) && video.getSubsrc().equals(
                        playRecord.getSite()))) {
                    cloudLiteBean.setPlay_time(playRecord.getSeekHistory());
                }
            }
            List<CloudLiteEpiBean> epiList = new ArrayList<CloudLiteEpiBean>();
            CloudLiteEpiBean bean = null;
            for (Episode epi : list){
                bean = new CloudLiteEpiBean();
                bean.setName(epi.getName());
                bean.setPorder(epi.getPorder());
                bean.setCloud_id(epi.getCloudId());
                bean.setGlobal_vid(epi.getGlobaVid());
                epiList.add(bean);
                bean = null;
            }
            cloudLiteBean.setEpisodeList(epiList);
        }
        //下架影片但还能在详情页点击播放的容错
        if(cloudLiteBean.getEpisodeList() == null || cloudLiteBean.getEpisodeList().size() == 0){
            ToastUtil.showShortToast(context, R.string.no_palydata_txt);
            return;
        }
        intent.putExtra("jsonData", (new Gson()).toJson(cloudLiteBean));

//        intent.putExtra("pcode", MoviesApplication.PLAYER_PCODE);
//        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        try {
            context.startActivity(intent);
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    /**
     * LiteApp下载链接地址请求异步任务类
     */
    private class LiteAppLinkUrlReqTask extends MoviesHttpAsyncTask<LiteAppLinkUrlInfo> {
        boolean toInstall = false;
        @Override
        public void netNull() {
            super.netNull();
        }

        @Override
        public void netErr(int updateId, String errMsg) {
            super.netErr(updateId, errMsg);
        }

        public LiteAppLinkUrlReqTask(Context context, boolean isToInstall) {
            super(context);
            toInstall = isToInstall;
        }

        @Override
        public LVideoDataHull<LiteAppLinkUrlInfo> doInBackground() {
            return MoviesHttpApi.requestLiteAppLinkUrl(new LiteAppLinkUrlParser());
        }

        @Override
        public void onPostExecute(int updateId, LiteAppLinkUrlInfo result) {
            LogUtils.e(UpdateService.TAG, "尝试下载LiteApp");
            if (result.getStatus().equals("1")) {

                SharePreferenceManager.saveVaule(MoviesApplication.getInstance(),
                        SharePreferenceManager.LITE_APP_MD5, result.getMd5());

                setDownloadState(DOWNLOAD_STATE_DOWNLOADING);
                if(toInstall){
                    showLiteProDialog(context);
                }
                LogUtils.e(UpdateService.TAG, "服务器返回数据成功");
                Intent intent = new Intent(context, UpdateService.class);
                intent.putExtra("url", result.getUrl());
                intent.putExtra("type", UpdateService.UPDATE_TYPE_LITE_APP);
                intent.putExtra("isToInstall", toInstall);
                context.startService(intent);
            } else {
                LogUtils.e(UpdateService.TAG, "服务器返回数据失败");
            }
        }
    }

    public void setDownloadState(int state) {
        mDownloadState = state;
    }

    public int getDownloadState() {
        return mDownloadState;
    }

    public boolean getLiteAppFuncSwitch() {
        return mLiteAppFuncSwitch;
    }

    public void setLiteAppFuncSwitch(boolean onOff) {
        mLiteAppFuncSwitch = onOff;
    }

    /**
     * 显示网络对话框
     */
    public void showNetDialog(Activity context) {
        int netType = NetWorkTypeUtils.getNetType();
        switch (netType) {
            case NetWorkTypeUtils.NETTYPE_NO:
                ToastUtil.showShortToast(context, R.string.neterror);
                break;
            case NetWorkTypeUtils.NETTYPE_WIFI:
                excuteDownLiteAppLogic(context);
                break;
            case NetWorkTypeUtils.NETTYPE_2G:
                DialogUtil.getInstance(context).liteAPPDownNetDialog(context);
                break;
            case NetWorkTypeUtils.NETTYPE_3G:
                DialogUtil.getInstance(context).liteAPPDownNetDialog(context);
                break;
        }
    }

    public void excuteDownLiteAppLogic(Context context) {
        if (isApkFileExist(context)) {
            LogUtils.e(UpdateService.TAG, "detail apk exist");
            if (mDownloadState != DOWNLOAD_STATE_DOWNLOADING) {
                String filePath = Environment.getExternalStorageDirectory().getPath() + "/" + LiteAppManager.LITE_APP_FILE_NAME;
                String md5 = SharePreferenceManager.getVaule(context, SharePreferenceManager.LITE_APP_MD5, "");
                if (TextUtils.isEmpty(md5)? true : md5.equals(MD5Utils.md5File(filePath))) {
                    File file = new File(Environment.getExternalStorageDirectory(), LITE_APP_FILE_NAME);
                    Intent intent = new Intent();
                    //执行动作
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    //执行的数据类型
                    if(Build.VERSION.SDK_INT >= 24){
                        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        Uri contentUri = FileProvider.getUriForFile(context, context.getPackageName(), file);
                        intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
                    }else{
                        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
                    }
                    context.startActivity(intent);
                }else{
                    deleteApkFile(context);
                    setDownloadState(DOWNLOAD_STATE_NONE);
                    downloadSilent(context, true);
                }
                LogUtils.e(UpdateService.TAG, "detail local exist apk and need delete");

            } else{
                LogUtils.e(UpdateService.TAG, "isdowning");
                showLiteProDialog(context);
            }
        } else {
            LogUtils.e(UpdateService.TAG, "detail apk not exist");
            downloadSilent(context, true);
        }
    }

    /**
     * 显示安装进度弹框
     *
     * @param context
     */
    public void showLiteProDialog(final Context context) {
        ((Activity) context).runOnUiThread(new Runnable() {
            @Override
            public void run() {

                progressDialog = new LiteProgressDialog(context, R.style.noHeadDialog);
                progressDialog.setCancelable(true);
                progressDialog.show();
            }
        });
    }

}
